package com.ego.cart.service.imlp;

import com.ego.auth.entity.UserInfo;
import com.ego.cart.feign.GoodsFeginClent;
import com.ego.cart.interceptor.AuthInterceptor;
import com.ego.cart.service.CartService;
import com.ego.cart.vo.Cart;
import com.ego.common.utils.JsonUtils;
import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.item.pojo.Sku;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private GoodsFeginClent goodsFeginClent;

    static final String KEY_PREFIX = "ego:cart";

    @Override
    public void addCart(Cart cart) {

        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        try {
            // 获取登录用户
            UserInfo userInfo = AuthInterceptor.getUserInfo();
            String userKey = KEY_PREFIX + userInfo.getId();
            String skuId = cart.getSkuId().toString();
            Integer num = cart.getNum();
            //判断该sku是否存在购物车中
            Boolean hasKey = opsForHash.hasKey(userKey, skuId);
            if (hasKey) {//存在->数量累加
                String cartJson = (String) opsForHash.get(userKey, skuId);
                cart = JsonUtils.parse(cartJson, Cart.class);//将cart转成对象
                cart.setNum(cart.getNum()+num);
            }else {//不存在->新增对象
                Sku sku = goodsFeginClent.querySkuById(Long.valueOf(skuId));
                cart.setPrice(sku.getPrice());
                cart.setImage(sku.getImages());
                cart.setOwnSpec(sku.getOwnSpec());
                cart.setTitle(sku.getTitle());
            }
            //写到redis
            opsForHash.put(userKey,skuId,JsonUtils.serialize(cart));
        } catch (Exception e){
            EgoException.error(log, ExceptionEnum.CART_ADD_ERROR,e);
        }
    }

    @Override
    public List<Cart> findAll() {
        // 获取登录用户
        UserInfo userInfo = AuthInterceptor.getUserInfo();
        String userKey = KEY_PREFIX + userInfo.getId();
        //将json转换为对象
        List<Cart> cartList = stringRedisTemplate.opsForHash()
                .values(userKey)
                .stream().map(cartJson -> JsonUtils.parse(cartJson.toString(), Cart.class))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cartList)){
            return null;
        }
        return cartList;
    }

    @Override
    public void updateNum(Long skuId, Integer num) {
        // 获取登录用户
        UserInfo userInfo = AuthInterceptor.getUserInfo();
        String key = KEY_PREFIX + userInfo.getId();
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        // 获取购物车
        String json = hashOps.get(skuId.toString()).toString();
        Cart cart = JsonUtils.parse(json, Cart.class);
        cart.setNum(num);
        // 写入购物车
        hashOps.put(skuId.toString(), JsonUtils.serialize(cart));
    }

    @Override
    public void deleteCart(String skuId) {
        // 获取登录用户
        UserInfo user = AuthInterceptor.getUserInfo();
        String key = KEY_PREFIX + user.getId();
        stringRedisTemplate.opsForHash().values(key).remove(skuId);
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(key);
        hashOps.delete(skuId);
    }
}
